package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Util.CurrentUserContextHolders;
import com.qk.common.constants.BusinessStatusConstants;
import com.qk.common.constants.ClueStatusConstants;
import com.qk.common.constants.ClueTrackType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluePoolDO;
import com.qk.dto.Clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: zyx
 * @created: 2025-10-13-17:17
 * @description:
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public void add(ClueDTO dto) {
        //参数校验
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //补全参数
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }

    @Override
    public PageResult<ClueDO> selectPage(ClueListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClueDO> page = this.baseMapper.selectByPage(dto);
        return PageResult.<ClueDO>builder()
                .total((int) page.getTotal()).rows(page.getResult()).build();
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        //根据ID获取线索信息
        Clue clue = this.baseMapper.selectById(id);
        //获取跟进人员姓名
        String assignName = userMapper.getUserById(clue.getUserId()).getName();
        //根据线索ID获取线索跟进记录
        List<ClueTrackRecord> trackRecords = clueTrackRecordMapper.selectList(Wrappers.<ClueTrackRecord>lambdaQuery()
                .in(ClueTrackRecord::getClueId, id));
        //封装VO
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.TrackRecordVO> list= trackRecords.stream().map(item -> {
            ClueVO.TrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.TrackRecordVO.class);
            vo.setAssignName(assignName);
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    @Transactional
    @Override
    public void followUpClue(UpdateClueDTO dto) {
        //拿到线索基础信息拷贝到新的Clue对象中
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (Objects.equals(clue.getStatus(), ClueStatusConstants.WAIT_FOLLOW_UP)) {
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        //更新线索信息
        this.baseMapper.updateById(clue);
        //拿到线索跟进记录信息拷贝到新的ClueTrackRecord对象中
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        //补全参数
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(dto.getId());
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setType(ClueTrackType.NORMAL);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        //插入线索跟进记录
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        //更新线索信息
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVERT_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        //将线索信息组装成商机并添加到数据库
        Business business = BeanUtil.copyProperties(clue, Business.class);
        //处理数据
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setClueId(id);
        business.setStatus(BusinessStatusConstants.TO_BE_ALLOCATED);
        this.businessMapper.insert(business);

    }

    @Override
    public void fakeClue(Integer id, FalseDTO dto) {
        //更新线索信息
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        //插入线索跟进记录
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(clue, ClueTrackRecord.class);
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(id);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setType(ClueTrackType.FAKE);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setRecord(dto.getRemark());
        clueTrackRecord.setFalseReason(dto.getReason());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public PageResult<CluePoolDO> poolPage(CluePoolListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<CluePoolDO> page = this.baseMapper.selectPoolPage(dto);
        return PageResult.<CluePoolDO>builder()
                .total((int) page.getTotal()).rows(page.getResult()).build();
    }
}
